package com.token.iot.bratterycharging.gateway.server;



import org.springframework.stereotype.Component;

import com.outstanding.framework.base.SpringContextHolder;
import com.token.iot.bratterycharging.gateway.utils.ByteUtil;

import org.springframework.beans.factory.annotation.Value;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.bytes.ByteArrayDecoder;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import io.netty.handler.timeout.IdleStateHandler;

@Component("bratteryChargingServerInitializer")
public class BratteryChargingServerInitializer extends ChannelInitializer<SocketChannel> {

	@Value("${heartbeat.interval:60}")
	private int heartbeatInterval;

	@Override
	protected void initChannel(SocketChannel ch) throws Exception {
		ChannelPipeline pipeline = ch.pipeline();

		/*
		 * 使用ObjectDecoder和ObjectEncoder 因为双向都有写数据和读数据，
		 * 所以这里需要两个都设置 如果只读，那么只需要ObjectDecoder即可
		 */
		//pipeline.addFirst("lengthdecoder", new GuardLengthFieldBasedFrameDecoder(255, 2, 1));
		//pipeline.addFirst("lengthdecoder", new LengthFieldBasedFrameDecoder(255, 1, 3, 1, 0));
		//增加一个结束符过滤器
		ByteBuf delimiter = Unpooled.copiedBuffer(ByteUtil.END);
		pipeline.addFirst(new DelimiterBasedFrameDecoder(20048,delimiter));
		
		pipeline.addLast("decoder", new ByteArrayDecoder());
		pipeline.addLast("encoder", new ByteArrayEncoder());
		
		// 句柄状态，3分钟无数据过来读空闲 1分钟写空闲
		pipeline.addLast("idleStateHandler", new IdleStateHandler(2*heartbeatInterval , 10*heartbeatInterval, 0)); 
		pipeline.addLast("keepalive", (ChannelHandler) SpringContextHolder.getBean("heartBeat"));
		pipeline.addLast(getServiceHandler());
	}

	public ChannelHandler getServiceHandler() {
		return (ChannelHandler) SpringContextHolder.getBean("bratterChargingHandler");
	}

}
